<template>
  <div style="height: 10vh;background-color:#fff;padding:10px 20px;">
    <!-- 搜索区域 -->
    <el-card style="height: 100%;">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" @submit.prevent="queryForm" class="searchForm">
        <el-form-item label="规则编号" prop="ruleNum">
          <el-select v-model="searchForm.ruleNum" placeholder="请选择规则编号" filterable clearable>
            <el-option v-for="rule in ruleOptions.ruleNums" :key="rule.value" :label="rule.label" :value="rule.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="规则名称" prop="ruleName">
          <el-select v-model="searchForm.ruleName" placeholder="请选择规则名称" filterable clearable>
            <el-option v-for="rule in ruleOptions.ruleNames" :key="rule.value" :label="rule.label" :value="rule.value" />
          </el-select>
        </el-form-item>

        <!-- 小时计费 -->
        <el-form-item label="小时计费" prop="hourlyBilling">
          <el-select v-model="searchForm.hourlyBilling" placeholder="请选择小时计费(元)" filterable clearable>
            <el-option v-for="rule in ruleOptions.hourlyBillings" :key="rule.value" :label="rule.label" :value="rule.value" />
          </el-select>
        </el-form-item>

        <!-- 计费上限 -->
        <el-form-item label="计费上限" prop="billLimit">
          <el-select v-model="searchForm.billLimit" placeholder="请选择计费上限(元)" filterable clearable>
            <el-option v-for="rule in ruleOptions.billLimits" :key="rule.value" :label="rule.label" :value="rule.value" />
          </el-select>
        </el-form-item>

        <!-- 免费时长 -->
        <el-form-item label="免费时长" prop="freeTime">
          <el-select v-model="searchForm.freeTime" placeholder="请选择免费时长(分钟)" filterable clearable>
            <el-option v-for="rule in ruleOptions.freeTimes" :key="rule.value" :label="rule.label" :value="rule.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="计费方式" prop="billMode">
          <el-select v-model="searchForm.billMode" placeholder="请选择计费方式" filterable clearable>
            <el-option v-for="mode in billModes" :key="mode.value" :label="mode.label" :value="mode.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true">
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" :loading="loading" @click="queryForm">查询</el-button>
          <el-button type="primary" @click="openDialog('create')">新建</el-button>
          <el-button
              :disabled="selectedRows.length === 0"
              :style="{ backgroundColor: selectedRows.length === 0 ? '#ffcccc' : '#ff4d4f', color: '#fff' }"
              @click="batchDelete"
          >
            删除
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <!-- 编辑/新建弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="70vh" @close="resetDialogForm">
    <el-form :model="dialogForm" :rules="dialogRules" ref="dialogFormRef" label-width="140px">
      <el-row>
        <el-col :span="12">
          <!-- 计费规则编号 -->
          <el-form-item label="计费规则编号" prop="ruleNum">
            <el-input v-model="dialogForm.ruleNum" placeholder="请输入规则编号" style="width: 80%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 计费规则名称 -->
          <el-form-item label="计费规则名称" prop="ruleName">
            <el-input v-model="dialogForm.ruleName" placeholder="请输入规则名称" style="width: 80%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 计费方式 -->
          <el-form-item label="计费方式" prop="billMode">
            <el-select v-model="dialogForm.billMode" placeholder="请选择计费方式" style="width: 80%" filterable>
              <el-option v-for="mode in billModes" :key="mode.value" :label="mode.label" :value="mode.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 免费时长 -->
          <el-form-item label="免费时长(分钟)" prop="freeTime">
            <el-input-number v-model="dialogForm.freeTime" :min="0" style="width: 80%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 小时价格 -->
          <el-form-item label="每小时价格(元)" prop="hourlyBilling">
            <el-input-number
                v-model="dialogForm.hourlyBilling"
                :min="0"
                :step="0.1"
                style="width: 80%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 24h收费限额 -->
          <el-form-item label="24h收费限额(元)" prop="billLimit">
            <div style="display: flex; align-items: center; gap: 10px">
              <el-input-number
                  v-model="dialogForm.billLimit"
                  :min="0"
                  :step="0.1"
                  style="width: 55%"
              />
              <span style="color: #999;font-size: 12px;">
              {{ dialogForm.billMode === '按次计费' ? '与小时价格保持一致' : '0表示无上限' }}
            </span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计费开始时间" prop="startTime">
            <el-time-picker
                v-model="dialogForm.startTime"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                placeholder="选择开始时间"
                style="width: 80%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计费结束时间" prop="endTime">
            <el-time-picker
                v-model="dialogForm.endTime"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                placeholder="选择结束时间"
                style="width: 80%"
            />
          </el-form-item>
        </el-col>
        <!-- 计费规则提示 -->
        <el-form-item label="计费提示">
          不足一小时按一小时计费。
        </el-form-item>
      </el-row>
    </el-form>
    <template #footer>
      <div style="display: flex;justify-content: center;gap: 20px;">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" :loading="saving" @click="saveDialog">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 计费规则列表和分页区域 -->
  <el-card style="margin: 20px; height: 70vh; display: flex; flex-direction: column;">
    <!-- 表格容器 -->
    <div class="table-container">
      <el-table
          :data="ruleList"
          border
          v-loading="loading"
          @selection-change="handleSelectionChange"
          ref="tableRef"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="ruleNum" label="规则编号" align="center" />
        <el-table-column prop="ruleName" label="规则名称" align="center" />
        <el-table-column prop="billMode" label="计费方式" align="center" />
        <el-table-column prop="hourlyBilling" label="小时收费(元)" align="center" />
        <el-table-column prop="billLimit" label="费用上限(元)" align="center" />
        <el-table-column prop="freeTime" label="免费时长(分钟)" align="center" />
        <el-table-column prop="billTime" label="计费时段" align="center">
          <template #default="scope">
            {{ `${scope.row.startTime}-${scope.row.endTime}` }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <el-table-column prop="updateTime" label="更新时间" align="center" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="openDialog('edit', scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页容器 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { logOperation } from '@/utils/log';

// 定义后端API接口路径
const API_URL = import.meta.env.VITE_API_BASE_URL;

// 计费方式选项
const billModes = ref([
  { label: '按次计费', value: '按次计费' },
  { label: '按时计费', value: '按时计费' }
]);

// 搜索表单
const searchForm = ref({
  ruleNum: '',
  ruleName: '',
  hourlyBilling: '',
  billLimit: '',
  freeTime: '',
  billMode: ''
});
const searchFormRef = ref(null);

// 表格和下拉框数据
const ruleList = ref([]);
const ruleOptions = ref({
  ruleNums: [],
  ruleNames: [],
  hourlyBillings: [],
  billLimits: [],
  freeTimes: []
});

// 分页相关
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('');
const dialogForm = ref({
  id: null,
  ruleNum: '',
  ruleName: '',
  freeTime: 0,
  hourlyBilling: 0,
  billLimit: 0,
  billMode: '按时计费',
  startTime: '00:00:00', // 默认开始时间
  endTime: '23:59:59',   // 默认结束时间
  createTime: '',
  updateTime: ''
});

// 监听计费方式变化
watch(() => dialogForm.value.billMode, (newVal) => {
  if (newVal === '按次计费') {
    // 当选择按次计费时，如果小时计费有值，将其同步到计费上限
    if (dialogForm.value.hourlyBilling !== 0) {
      dialogForm.value.billLimit = dialogForm.value.hourlyBilling;
    }
  }
});

// 监听小时计费变化
watch(() => dialogForm.value.hourlyBilling, (newVal) => {
  if (dialogForm.value.billMode === '按次计费') {
    dialogForm.value.billLimit = newVal;
  }
});

// 监听计费上限变化
watch(() => dialogForm.value.billLimit, (newVal) => {
  if (dialogForm.value.billMode === '按次计费') {
    dialogForm.value.hourlyBilling = newVal;
  }
});

const dialogFormRef = ref(null);
const dialogRules = {
  ruleNum: [{ required: true, message: '请输入规则编号', trigger: 'blur' }],
  ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  freeTime: [{ required: true, message: '请输入免费时长', trigger: 'blur' }],
  hourlyBilling: [{ required: true, message: '请输入小时价格', trigger: 'blur' }],
  billLimit: [{ required: true, message: '请输入收费限额', trigger: 'blur' }],
  billMode: [{ required: true, message: '请选择计费方式', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
};

// 多选框相关
const selectedRows = ref([]);
const tableRef = ref(null);

// 加载状态
const saving = ref(false);

// 查询计费规则列表（支持分页）
const queryForm = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm.value,
      page: currentPage.value,
      size: pageSize.value
    };
    const { data } = await axios.get(`${API_URL}/v1/bill-temp-rule/select`, { params });
    if (data.code === 2000) {
      ruleList.value = data.response || [];
      total.value = data.total || 0;
      updateOptions(data.response);
      ElMessage.success('数据加载成功');
    } else {
      ElMessage.error(`数据加载失败: ${data.response?.message || '未知错误'}`);
      ruleList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('查询错误:', error);
    ElMessage.error('请求异常');
    ruleList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 更新下拉框选项
const updateOptions = (rules) => {
  const uniqueRuleNums = new Map();
  const uniqueRuleNames = new Map();
  const uniqueHourlyBillings = new Map();
  const uniqueBillLimits = new Map();
  const uniqueFreeTimes = new Map();

  rules.forEach(item => {
    if (item.ruleNum) uniqueRuleNums.set(item.ruleNum, item.ruleNum);
    if (item.ruleName) uniqueRuleNames.set(item.ruleName, item.ruleName);
    if (item.hourlyBilling !== undefined) uniqueHourlyBillings.set(item.hourlyBilling, `${item.hourlyBilling}元`);
    if (item.billLimit !== undefined) uniqueBillLimits.set(item.billLimit, `${item.billLimit}元`);
    if (item.freeTime !== undefined) uniqueFreeTimes.set(item.freeTime, `${item.freeTime}分钟`);
  });

  ruleOptions.value.ruleNums = Array.from(uniqueRuleNums, ([value, label]) => ({ value, label }));
  ruleOptions.value.ruleNames = Array.from(uniqueRuleNames, ([value, label]) => ({ value, label }));
  ruleOptions.value.hourlyBillings = Array.from(uniqueHourlyBillings, ([value, label]) => ({ value, label }));
  ruleOptions.value.billLimits = Array.from(uniqueBillLimits, ([value, label]) => ({ value, label }));
  ruleOptions.value.freeTimes = Array.from(uniqueFreeTimes, ([value, label]) => ({ value, label }));
};

// 重置搜索表单
const resetForm = () => {
  searchFormRef.value.resetFields();
  currentPage.value = 1; // 重置到第一页
  queryForm();
};

// 打开弹窗
const openDialog = (type, row = {}) => {
  dialogVisible.value = true;
  dialogTitle.value = type === 'create' ? '新增计费规则' : '编辑计费规则';
  dialogForm.value = type === 'create'
      ? { id: null, ruleNum: '', ruleName: '', freeTime: 0, hourlyBilling: 0, billLimit: 0, billMode: '按时计费', startTime: '00:00:00', endTime: '23:59:59', createTime: '', updateTime: '' }
      : { ...row };
};

// 重置弹窗表单
const resetDialogForm = () => {
  dialogFormRef.value?.resetFields();
};

// 关闭弹窗
const closeDialog = () => {
  ElMessageBox.confirm('您确认要关闭本弹窗吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        dialogVisible.value = false;
      })
      .catch(() => {});
};

// 保存计费规则
const saveDialog = () => {
  dialogFormRef.value.validate(async (valid) => {
    if (!valid) return;
    saving.value = true;
    try {
      const url = `${API_URL}/v1/bill-temp-rule/save`;
      const method = dialogForm.value.id ? 'put' : 'post'; // 根据 id 判断使用 PUT 或 POST
      const { data } = await axios({ method, url, data: dialogForm.value });
      if (data.code === 2000) {
        ElMessage.success(dialogForm.value.id ? '更新成功' : '新建成功');
        dialogVisible.value = false;
        await queryForm();
        await logOperation('临停计费规则', `${dialogForm.value.id ? '更新' : '新建'}临停计费规则 ${dialogForm.value.ruleNum} ${dialogForm.value.ruleName}`);
      } else {
        ElMessage.error(`保存失败: ${data.response?.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('保存错误:', error);
      ElMessage.error('请求异常');
    } finally {
      saving.value = false;
    }
  });
};

// 处理多选框变化
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 抽象出的删除方法，支持单条和批量删除
const deleteRules = async (rows) => {
  const isBatch = Array.isArray(rows);
  const count = isBatch ? rows.length : 1;
  const ids = isBatch ? rows.map(row => row.id) : [rows.id];
  const confirmMessage = isBatch
      ? `您确认要删除 ${count} 个计费规则吗?`
      : '您确认要删除此计费规则吗?';

  try {
    await ElMessageBox.confirm(confirmMessage, '删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const url = isBatch ? `${API_URL}/v1/bill-temp-rule/batchDelete` : `${API_URL}/v1/bill-temp-rule/delete/${ids[0]}`;
    const method = isBatch ? 'post' : 'delete';
    const requestData = isBatch ? { ids } : null;

    const { data } = await axios({
      method,
      url,
      data: requestData
    });

    if (data.code === 2000) {
      ElMessage.success(isBatch ? '批量删除成功' : '删除成功');
      await queryForm();

      const logRows = isBatch ? rows : [rows];
      for (const row of logRows) {
        await logOperation('临停计费规则', `删除临停计费规则 ${row.ruleName}`);
      }

      if (isBatch) {
        selectedRows.value = [];
        tableRef.value.clearSelection();
      }
    } else {
      ElMessage.error(`删除失败: ${data.response?.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('删除错误:', error);
    ElMessage.error('请求异常');
  }
};

// 删除单个计费规则
const deleteRow = async (row) => {
  await deleteRules(row);
};

// 批量删除
const batchDelete = async () => {
  if (selectedRows.value.length === 0) return;
  await deleteRules(selectedRows.value);
};

// 分页事件处理
const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryForm();
};

// 初始化加载
onMounted(() => {
  queryForm();
});
</script>

<style scoped>
.searchForm :deep(.el-select) {
  width: 15vh;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px; /* 预留分页空间 */
}

/* 分页容器样式 */
.pagination-container {
  padding: 10px 20px;
  text-align: center;
  background-color: #fff;
  min-height: 60px; /* 确保分页区域有足够高度 */
}
</style>